/*
 * Copyright (c) 2024. Shanghai HEADING information Engineering Co., Ltd. All rights reserved.
 */
package com.lovely602.thread.queue;


import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * @author lizhixing
 */
public class ProducerConsumerDemo {

  public static void main(String[] args) {
    BlockingQueue<Integer> queue = new LinkedBlockingQueue<>(10);

    Thread producerThread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          for (int i = 0; i < 100; i++) {
            System.out.println("Producing: " + i);
            queue.put(i);
            Thread.sleep(100); // 模拟生产数据的时间延迟
          }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    });

    Thread consumerThread = new Thread(new Runnable() {
      @Override
      public void run() {
        try {
          while (true) {
            int value = queue.take();
            System.out.println("Consuming: " + value);
            Thread.sleep(200); // 模拟消费数据的时间延迟
          }
        } catch (InterruptedException e) {
          Thread.currentThread().interrupt();
        }
      }
    });

    producerThread.start();
    consumerThread.start();
  }
}

